package com.home.cca.network;// com.home.cca.network.LoginRequest

import java.io.IOException;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginRequest {

    private static final String URL = ApiClient.getBaseUrl() + "/RightFrame/Home/Login";

    public static String login() throws IOException {
        RequestBody body = new FormBody.Builder()
                .add("loginName", "15930935383")
                .add("loginPwd", "4683fabe2b0a54e5c0610323653867ce92bdc7304781e6049d97951be7c98e09")
                .add("Validate", "")
                .build();

        Request request = new Request.Builder()
                .url(URL)
                .post(body)
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Origin", "https://sa.lystcgjg.com:8880")
                .header("Referer", "https://sa.lystcgjg.com:8880/RightFrame")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("docktoken", "null")
                .header("key", "15930935383")
                .header("Sec-Ch-Ua", "\"Chromium\";v=\"136\", \"Microsoft Edge\";v=\"136\", \"Not.A/Brand\";v=\"99\"")
                .header("Sec-Ch-Ua-Mobile", "?0")
                .header("Sec-Ch-Ua-Platform", "\"Windows\"")
                .header("Sec-Fetch-Site", "same-origin")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Dest", "empty")
                .header("Connection", "keep-alive")
                .build();

        try (Response response = ApiClient.getClient().newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("登录失败: HTTP " + response.code());
            }

            // 提取 Cookie
            List<String> cookies = response.headers("Set-Cookie");
            StringBuilder cookieBuilder = new StringBuilder();
            for (String cookie : cookies) {
                if (cookie.contains("MysafeMisWeb")) {
                    String[] parts = cookie.split(";");
                    cookieBuilder.append(parts[0]).append("; ");
                }
            }
            String sessionCookie = cookieBuilder.toString().trim();
            if (sessionCookie.isEmpty()) {
                throw new IOException("未收到有效的会话 Cookie");
            }

            return sessionCookie;
        }
    }
}